package com.lglbc.oauth2.config.details.client;

import com.lglbc.oauth2.entity.OauthClient;
import com.lglbc.oauth2.enums.PasswordEncoderTypeEnum;
import com.lglbc.oauth2.service.OauthClientService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author： 乐哥聊编程(全平台同号)
 */
@Service
@RequiredArgsConstructor
public class ClientDetailsServiceImpl implements ClientDetailsService {
    private final OauthClientService oauthClientService;

    @Override
    public ClientDetails loadClientByClientId(String clientId) {
        // 获取client信息
        OauthClient oauthClient = oauthClientService.lambdaQuery().eq(OauthClient::getClientId, clientId).one();
        if (Objects.nonNull(oauthClient)) {
            BaseClientDetails clientDetails = new BaseClientDetails(
                    oauthClient.getClientId(),
                    oauthClient.getResourceIds(),
                    oauthClient.getScope(),
                    oauthClient.getAuthorizedGrantTypes(),
                    oauthClient.getAuthorities(),
                    oauthClient.getWebServerRedirectUri());
            clientDetails.setClientSecret(PasswordEncoderTypeEnum.NOOP.getPrefix() + oauthClient.getClientSecret());
            clientDetails.setAccessTokenValiditySeconds(oauthClient.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(oauthClient.getRefreshTokenValidity());
            return clientDetails;
        } else {
            throw new NoSuchClientException("没找到客户端信息");
        }
    }
}
